import React, { useState } from 'react';
import { IPublicModelPluginContext } from '@alilc/lowcode-types';
import { buildComponents, assetBundle, AssetLevel, AssetLoader } from '@alilc/lowcode-utils';
import { injectComponents } from '@alilc/lowcode-plugin-inject';

const MyMenuPlugin = (ctx: IPublicModelPluginContext) => {
  return {
    // 插件对外暴露的数据和方法
    exports() {
      return {
        data: '你可以把插件的数据这样对外暴露',
        func: () => {
          console.log('方法也是一样');
        },
      };
    },
    // 插件的初始化函数，在引擎初始化之后会立刻调用
    init() {
      // 你可以拿到其他插件暴露的方法和属性
      // const { data, func } = ctx.plugins.pluginA;
      // func();

      // console.log(options.name);

      // 往引擎增加面板
      ctx.skeleton.add({
        area: 'leftArea',
        name: 'myMenuPlugin',
        type: 'PanelDock',
        props: {
          description: '菜单',
        },
        content: () => <MyComponent ctx={ctx} />,
      });

      ctx.logger.log('打个日志');
    },
  };
};

// 插件名，注册环境下唯一
MyMenuPlugin.pluginName = 'LowcodePluginPluginDemo';
MyMenuPlugin.meta = {
  // 依赖的插件（插件名数组）
  dependencies: [],
  engines: {
    lowcodeEngine: '^1.0.0', // 插件需要配合 ^1.0.0 的引擎才可运行
  },
};

export default MyMenuPlugin;





// import lowcodeSchema from '../../services/mySchema.json'
function MyComponent({ ctx }: { ctx: IPublicModelPluginContext }) {
  const [data, setData] = useState({});
  const { material } = ctx;

  function showPage(schemaName: string) {
    console.log(schemaName);
    ctx.project.importSchema(require('../../services/' + schemaName));

  }

  async function getSchemaAndComponents() {
    const packages = JSON.parse(window.localStorage.getItem('packages') || '{}');
    const projectSchema = JSON.parse(window.localStorage.getItem('projectSchema') || '');
    const { componentsMap: componentsMapArray, componentsTree } = projectSchema;
    const componentsMap: any = {};
    componentsMapArray.forEach((component: any) => {
      componentsMap[component.componentName] = component;
    });
    const schema = componentsTree[0];

    const libraryMap = {};
    const libraryAsset = [];
    packages.forEach(({ package: _package, library, urls, renderUrls }) => {
      libraryMap[_package] = library;
      if (renderUrls) {
        libraryAsset.push(renderUrls);
      } else if (urls) {
        libraryAsset.push(urls);
      }
    });


    const assetLoader = new AssetLoader();
    await assetLoader.load(libraryAsset);
    const components = await injectComponents(buildComponents(libraryMap, componentsMap));

    return {
      schema, 
      components,
    };
  }

  // 其他代码...

  return (
    <div style={{ padding: '10px' }}>
      <p onClick={() => showPage('mySchema.json')} style={{ cursor:'pointer' }}>首页</p>
      <p onClick={() => showPage('myLoginSchema.json')} style={{ cursor:'pointer' }}>登陆页</p>
    </div>
  );
}
